<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

// [ 应用入口文件 ]
namespace think;


use app\model\TaskModel;
use app\model\TaskUserResultModel;

require __DIR__ . '/vendor/autoload.php';
$app = new App();
$http = $app->http;
$http->run();

$TaskModel = new TaskModel();
$TaskModel->startTrans();
try {
    $data = $TaskModel->field('id,user_count,rating_scale_count')->select()->toArray();
    $TaskUserResultModel = new TaskUserResultModel();
    foreach ($data as $value) {
        $warning_num = $TaskUserResultModel->where([
            ['task_id', '=', $value['id']],
            ['is_warning', '=', 1]
        ])->distinct('uid')->count('uid');
        $user_complete_num = $TaskUserResultModel->where('task_id', '=', $value['id'])
            ->field('uid')
            ->group('uid')
            // 统计不同任务的完成次数（去重任务ID）
            ->having('count(id) = '.$value['rating_scale_count'])
            ->count();
        if (!empty($user_complete_num)){
            $user_complete_rate = number_format(($user_complete_num / $value['user_count']) * 100, 2);
        }else{
            $user_complete_rate = 0;
        }
        $TaskModel->where('id','=',$value['id'])->update([
            'user_complete_num' => $user_complete_num,
            'user_complete_rate' => $user_complete_rate,
            'warning_num' => $warning_num,
        ]);
    }
    $TaskModel->commit();
    echo '恢复成功!';
} catch (\Exception $e) {
    $TaskModel->rollback();
    echo error($e->getMessage(), $e->getCode(),[
        'line' => $e->getLine(),
        'file' => $e->getFile(),
    ]);
}